<template>
  <div class="container">
    <div class="search-container">
      <div class="search-option-row"> 
        <label class="search-option-label">公司</label>
        <div class="search-option-col">
        <el-input v-model="listQuery.company_name" class="select-item" placeholder="请输入" style="width: 180px;" ></el-input>
        </div>
        <label class="search-option-label">公司类型</label>
        <div class="search-option-col">
        <el-select v-model="listQuery.company_type" placeholder="请选择">
          <el-option
            v-for="item in company_category_options"
            :key="item.id"
            :label="item.label"
            :value="item.id">
          </el-option>
        </el-select>
        </div>
        <label class="search-option-label">行业</label>
        <div class="search-option-col">
        <treeselect
          class="select-item" 
          :load-options="loadChildrenOptions"
          :multiple="true"
          :valueConsistsOf="valueConsistsOf"
          :options="industry_options"
          placeholder="请选择"
          v-model="listQuery.industry">
           <label slot="option-label" slot-scope="{ node, shouldShowCount, count, labelClassName, countClassName }" :class="labelClassName">
           <span :title="node.label">{{ node.label }}</span>
          </label>
        </treeselect>
        </div>
        <label class="search-option-label">城市</label>
        <div class="search-option-col">
        <treeselect
          class="select-item" 
          :load-options="loadChildrenOptions"
          :multiple="true"
          :valueConsistsOf="valueConsistsOf"
          :options="city_options"
          placeholder="请选择"
          v-model="listQuery.city"
          />  
        </div>
      </div>
      <div class="search-option-row"> 
        <label class="search-option-label">BD</label>
        <div class="search-option-col">
        <el-select
          v-model="listQuery.bd"
          filterable
          clearable
          collapse-tags
          placeholder="请选择">
          <el-option
            v-for="item in userOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        </div>
      </div>
      <div class="search-button-row" >
        <label class="search-button-label"></label>
        <div class="search-button-col">
        <el-button size="mini" type="primary" icon="el-icon-search" @click="handleFilter" round>搜索</el-button>
        <el-button size="mini" type="primary" icon="el-icon-refresh" @click="clearOptions" round>清空</el-button>
        </div>
      </div>  
    </div>
    <div class="table-header-row">
      <div class="table-header-button">
          <el-button plain size="mini" @click="handleCreate" >新增客户</el-button>
          <el-button plain size="mini" v-if="hasRoles(['COMPANY_BD_UPDATE', 'SUPER_ADMIN'])"  :disabled="updateBDDisable" @click="batchUpdateBD">维护BD</el-button>
          <el-button plain size="mini" @click="toggleSelection()">取消选择</el-button>
      </div>
    </div>

    <div class="table-container">
      <el-table v-loading="listLoading" border ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column fixed type="selection" width="55">
        </el-table-column>
        <el-table-column fixed label="公司名称" width="200">
          <template slot-scope="scope">
            <span class="link-type" @click="handleViewCompanyDesc(scope.row)">
              {{scope.row.company_name}}<svg-icon icon-class="share-square" />
            </span>
          </template>
        </el-table-column>
         <el-table-column label="城市" width="50">
          <template slot-scope="scope">{{ scope.row.city | cityValFilter }}</template>
        </el-table-column>
        <el-table-column label="行业" min-width="80">
          <template slot-scope="scope">{{ scope.row.industry | industryFilter}}</template>
        </el-table-column>
        <el-table-column label="BD" min-width="80">
          <template slot-scope="scope">
            <span v-if="scope.row.bd && scope.row.bd.username" >
              {{ scope.row.bd.username }}
            </span> 
            <span v-else>暂无</span>
          </template>
        </el-table-column>
        <el-table-column label="联系人" width="70"> 
          <template slot-scope="scope">
            <span class="link-type" @click="handleViewContactPeople(scope.row)">
              {{ scope.row.contact_people_count }}<svg-icon icon-class="share-square" />
            </span>
          </template>
        </el-table-column>
        <el-table-column label="在职人数" width="70">
          <template slot-scope="scope">
            <span class="link-type" @click="handleViewCandidates(scope.row)">
            {{ scope.row.active_candidates_count }}<svg-icon icon-class="share-square" />
            </span>
          </template>
        </el-table-column>
        <el-table-column label="进展中的项目" width="70">
          <template slot-scope="scope">
            <span class="link-type" @click="handleViewProject(scope.row)">
            {{ scope.row.project_live_count }}<svg-icon icon-class="share-square" />
            </span>
          </template>
        </el-table-column>
        <el-table-column label="类型" width="100">
          <template slot-scope="scope">
            <el-tag>{{ scope.row.company_type | companyTypeFilter }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" min-width="200">
          <template slot-scope="scope"> 
          <span v-if="scope.row.comments && scope.row.comments.length >0" >{{ scope.row.comments[0].comment || ''}}</span>
          <span v-else></span>
          <span v-if="scope.row.comments && scope.row.comments.length >1" class="link-type" @click='handleShowMoreComments(scope.row)'>更多</span>
          <span v-else></span>
          <el-button icon="el-icon-tickets" @click='handleAddComment(scope.row)' size="mini" >新增</el-button>
          </template>
        </el-table-column>
        <el-table-column label="最新更新" width="80">
          <template slot-scope="scope">{{ scope.row.newest_update_date | timeFromNowFilter }}</template>
        </el-table-column>
        <el-table-column  label="操作" width="80"> 
          <template slot-scope="scope">
              <el-dropdown @command="handleCommand"  trigger="click">
              <span class="el-dropdown-link">
                <svg-icon icon-class="code" />
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-if="hasRoles(['COMPANY_INFO_UPDATE', 'SUPER_ADMIN']) || businessOperable(scope.row) || isAllowMiniRole('CHECK_ALL', scope.row) || (this.current_user_id === scope.row.create_id)" :command='{type:"edit", data: scope.row}' >编辑</el-dropdown-item>
                <el-dropdown-item v-if="hasRoles(['COMPANY_BD_UPDATE', 'SUPER_ADMIN']) || isAllowMiniRole('CHECK_ALL', scope.row)" :command='{type:"update_bd", data: scope.row}' >维护BD</el-dropdown-item>
                <el-dropdown-item v-if="hasRoles(['SUPER_ADMIN'])" :command='{type:"del_company", data: scope.row}' >删除客户</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
      <el-pagination background 
        @size-change="handleSizeChange" 
        @current-change="handleCurrentChange" 
        :current-page="current_page" :page-sizes="[10,20,30, 50]" 
        :page-size="listQuery.limit" layout="total, sizes, prev, pager, next" 
        :total="total"
        >
      </el-pagination>
      </div>
    </div>
    <el-dialog title="历史备注" :visible.sync="dialogHistoryCommentsVisible" append-to-body>
      <el-table :data="this.history_comments" border fit highlight-current-row style="width: 100%" >
        <el-table-column  label="备注" width="500px"> 
          <template slot-scope="comment_scope">
            {{comment_scope.row.comment}}
          </template>
        </el-table-column>
        <el-table-column label="时间" width="100px"> 
          <template slot-scope="comment_scope">
            {{comment_scope.row.comment_date | timeFilter('{y}-{m}-{d} {h}:{i}') }}
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
      <el-pagination background 
        @size-change="handleHistoryCommentsSizeChange" 
        @current-change="handleHistoryCommentsCurrentChange" 
        :current-page="history_comments_current_page" :page-sizes="[10,20,30, 50]" 
        :page-size="historyCommentsListQuery.limit" layout="total, sizes, prev, pager, next" 
        :total="historyCommentstotal"
        >
      </el-pagination>
      </div>
    </el-dialog>
    <el-dialog title="新增备注" :visible.sync="commentDialogVisible" append-to-body>
      <el-form  :rules="comment_rules" ref="commentForm" :model="comment_temp" label-position="left" label-width="70px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="备注" prop="comment">
          <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="comment_temp.comment"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="commentDialogVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button type="primary" @click="addComment">{{$t('table.confirm')}}</el-button>
      </div>
    </el-dialog>
    <CompanyDialog :id="company_dialog.id" :visible="company_dialog.visible" :status="company_dialog.status" @closeDialog="closeDialog"> </CompanyDialog>
    
    <el-tooltip placement="top" content="tooltip">
      <back-to-top transitionName="fade" :customStyle="myBackToTopStyle" :visibilityHeight="300" :backPosition="50"></back-to-top>
    </el-tooltip>

    <el-dialog title="维护BD" :visible.sync="updateBDDialogVisible" append-to-body>
      <el-form  :rules="bd_rules" ref="bdForm" :model="bd_temp" label-position="left" label-width="70px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="客户">
          <div v-for="item in company_group_for_bd" :key="item"> 
            {{item}} 
          </div>
        </el-form-item>
        <el-form-item label="BD" prop="bd">
          <el-select
          v-model="bd_temp.bd"
          filterable
          clearable
          collapse-tags
          placeholder="请选择">
          <el-option
            v-for="item in userOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateBDDialogVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button type="primary" @click="updateBD">{{$t('table.confirm')}}</el-button>
      </div>
    </el-dialog>
    <CompanyDialog :id="company_dialog.id" :visible="company_dialog.visible" :status="company_dialog.status" @closeDialog="closeDialog"> </CompanyDialog>
    <el-tooltip placement="top" content="tooltip">
      <back-to-top transitionName="fade" :customStyle="myBackToTopStyle" :visibilityHeight="300" :backPosition="50"></back-to-top>
    </el-tooltip>
  </div>
</template>

<script>

import API from '@/utils/backend_api'
import Static_Data from '@/data/index'
import BackToTop from '@/components/BackToTop'
import CompanyDialog from '@/views/company/components/companyDialog'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
const simulateAsyncOperation = fn => {
  setTimeout(fn, 200)
}
export default {
  name: 'company',
  components: { Treeselect, BackToTop, CompanyDialog },
  data() {
    return {
      valueConsistsOf: 'ALL',
      current_user_id: this.$store.getters.userId,
      current_user_roles: this.$store.getters.roles,
      current_users_group: this.$store.getters.usersList,
      MiniRole: Static_Data.mini_roles,
      updateBDDisable: true,
      updateBDDialogVisible: false,
      bd_rules: {
        bd: [
          { required: true, message: '必须填写', trigger: 'change' }
        ]
      },
      bd_temp: { bd: '', company_id: [] },
      company_group_for_bd: [],
      userOptions: this.$store.getters.usersList.map(item => ({ value: item.id, label: item.username + '(' + item.uid + ')' })),
      commentDialogVisible: false,
      dialogHistoryCommentsVisible: false,
      comment_rules: {
        comment: [
          { required: true, message: '必须填写', trigger: 'change' }
        ]
      },
      comment_temp: { comment: '' },
      company_dialog: {
        id: '',
        visible: false,
        status: ''
      },
      myBackToTopStyle: {
        right: '50px',
        bottom: '25px',
        width: '40px',
        height: '40px',
        'border-radius': '4px',
        'line-height': '45px', // 请保持与高度一致以垂直居中 Please keep consistent with height to center vertically
        background: '#e7eaf1'// 按钮的背景颜色 The background color of the button
      },
      total: 0,
      current_page: 1,
      city_arr: [],
      industry_arr: [],
      history_comments: [],
      history_comments_current_page: 1,
      historyCommentstotal: 0,
      historyCommentsListQuery: {
        page: 1,
        offset: 0,
        limit: 10,
        company_id: ''
      },
      listQuery: {
        page: 1,
        offset: 0,
        limit: 20,
        sort: '-CAST(newest_update_date AS SIGNED)',
        company_name: '',
        company_type: '',
        industry: [],
        city: [],
        bd: ''
      },
      city_options: Static_Data.city,
      industry_options: Static_Data.industry,
      company_category_options: Static_Data.company_type,
      listLoading: true,
      tableData: [],
      multipleSelection: []
    }
  },
  created() {
    this.getList()
  },
  filters: {
  },
  methods: {
    authMiniRole(miniRolekey, dept, office) {
      const isHasMiniRoleOffice = this.current_user_roles.some(my_role => my_role === (miniRolekey + '_' + this.MiniRole.MINI_P_OFFICE + '_' + office)) ||
        this.current_user_roles.some(my_role => my_role === (miniRolekey + '_' + this.MiniRole.MINI_P_OFFICE + '_ALL'))
      const isHasMiniRoleDept = this.current_user_roles.some(my_role => my_role === (miniRolekey + '_' + this.MiniRole.MINI_P_DEPT + '_' + dept)) ||
        this.current_user_roles.some(my_role => my_role === (miniRolekey + '_' + this.MiniRole.MINI_P_DEPT + '_ALL'))
      console.log('authMiniRole:', miniRolekey, isHasMiniRoleOffice, isHasMiniRoleDept, (isHasMiniRoleOffice && isHasMiniRoleDept))
      return (isHasMiniRoleOffice && isHasMiniRoleDept)
    },
    isAllowMiniRole(key, data) {
      if (data.create_id && data.create_id !== '') {
        let own_user = {}
        this.current_users_group.map(current_item => {
          if (current_item.id === data.create_id) {
            own_user = current_item
          }
        })
        // console.log('own_user:', own_user)
        return this.authMiniRole(key, own_user.department_id, own_user.office)
      }
      return false
    },
    businessOperable(data) {
      return ((data.bd && this.current_user_id === data.bd.id) || (data.create_id && this.current_user_id === data.create_id))
    },
    hasRoles(roles) {
      return this.current_user_roles.some(item => roles.indexOf(item) >= 0)
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      if (this.multipleSelection && this.multipleSelection.length > 0) {
        this.updateBDDisable = false
      } else {
        this.updateBDDisable = true
      }
    },
    batchUpdateBD() {
      this.bd_temp = { bd: '', company_id: [] }
      this.company_group_for_bd = []
      this.multipleSelection.map(item => {
        this.bd_temp.company_id.push(item.id)
        this.company_group_for_bd.push(item.company_name)
      })
      this.updateBDDialogVisible = true
      this.$nextTick(() => {
        this.$refs['bdForm'].clearValidate()
      })
    },
    handleDelCompany(data) {
      this.$confirm('此操作将删除该客户[' + data.company_name + '], 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        API.company.del(data.id).then(response => {
          for (const v of this.tableData) {
            if (v.id === data.id) {
              const index = this.tableData.indexOf(v)
              this.tableData.splice(index, 1)
              break
            }
          }
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleUpdateBD(data) {
      this.bd_temp = { bd: '', company_id: [data.id] }
      if (data.bd && data.bd.id) {
        this.bd_temp.bd = data.bd.id
      }
      this.company_group_for_bd = [data.company_name]
      this.updateBDDialogVisible = true
      this.$nextTick(() => {
        this.$refs['bdForm'].clearValidate()
      })
    },
    updateBD() {
      this.$refs['bdForm'].validate((valid) => {
        if (valid) {
          API.company.updateBD(this.bd_temp).then((response) => {
            console.log(response)
            for (const k of response.data) {
              for (const v of this.tableData) {
                if (v.id === k.id) {
                  const index = this.tableData.indexOf(v)
                  this.tableData.splice(index, 1, k)
                  break
                }
              }
            }
            this.$message({
              type: 'success',
              message: '更新成功!'
            })
            this.updateBDDialogVisible = false
            this.bd_temp = { bd: '', company_id: [] }
            this.company_group_for_bd = []
          })
        }
      })
    },
    handleAddComment(data) {
      this.comment_temp = { company_id: data.id, comment: '' }
      this.commentDialogVisible = true
      this.$nextTick(() => {
        this.$refs['commentForm'].clearValidate()
      })
    },
    addComment() {
      this.$refs['commentForm'].validate((valid) => {
        if (valid) {
          API.company.add_comment(this.comment_temp).then((response) => {
            for (const v of this.tableData) {
              if (v.id === this.comment_temp.company_id) {
                const index = this.tableData.indexOf(v)
                this.tableData.splice(index, 1, response.data)
                break
              }
            }
            this.commentDialogVisible = false
            this.comment_temp = { comment: '' }
          })
        }
      })
    },
    handleCommand(val) {
      if (val.type && val.data && val.type === 'view') {
        this.handleViewCompanyDesc(val.data)
      }
      if (val.type && val.data && val.type === 'edit') {
        this.handleUpdate(val.data)
      }
      if (val.type && val.data && val.type === 'update_bd') {
        this.handleUpdateBD(val.data)
      }
      if (val.type && val.data && val.type === 'del_company') {
        this.handleDelCompany(val.data)
      }
    },
    handleCreate() {
      this.company_dialog = {
        id: '',
        visible: true,
        status: 'create'
      }
    },
    handleUpdate(row) {
      if (row && row.id) {
        this.company_dialog = {
          id: row.id,
          visible: true,
          status: 'update'
        }
      }
    },
    closeDialog(val) {
      if (val && val.type === 'create_success' && val.data) {
        this.tableData.unshift(val.data)
      }
      if (val && val.type === 'update_success' && val.data) {
        for (const v of this.tableData) {
          if (v.id === val.data.id) {
            const index = this.tableData.indexOf(v)
            this.tableData.splice(index, 1, val.data)
            break
          }
        }
      }
      this.company_dialog = {
        id: '',
        visible: false,
        status: ''
      }
    },
    handleViewCompanyDesc(row) {
      /* 验证是否存在查看权限 */
      if (row && row.id) {
        this.$router.push({
          name: 'companyDetail',
          params: {
            id: row.id,
            name: row.company_name,
            tab: 'base'
          }
        })
      }
    },
    handleViewProject(row) {
      /* 验证是否存在查看权限 */
      if (row && row.id) {
        this.$router.push({
          name: 'companyDetail',
          params: {
            id: row.id,
            name: row.company_name,
            tab: 'project'
          }
        })
      }
    },
    handleViewCandidates(row) {
      /* 验证是否存在查看权限 */
      if (row && row.id) {
        this.$router.push({
          name: 'companyDetail',
          params: {
            id: row.id,
            name: row.company_name,
            tab: 'candidate'
          }
        })
      }
    },
    handleViewContactPeople(row) {
      /* 验证是否存在查看权限 */
      if (row && row.id) {
        this.$router.push({
          name: 'companyDetail',
          params: {
            id: row.id,
            name: row.company_name,
            tab: 'contact'
          }
        })
      }
    },
    closeCompanyDescDialog() {
      this.company_desc = {
        id: '',
        visible: false,
        header_name: '',
        tab: 'base'
      }
    },
    handleFilter() {
      this.getList()
    },
    clearOptions() {
      this.city_arr = []
      this.listQuery = {
        page: 1,
        offset: 0,
        limit: 20,
        sort: '-CAST(newest_update_date AS SIGNED)',
        company_name: '',
        company_type: '',
        industry: [],
        city: [],
        bd: ''
      }
    },
    getList() {
      this.listLoading = true
      console.log(this.listQuery)
      this.listQuery.departments = JSON.stringify(this.listQuery.departments_arr)
      API.company.all(this.listQuery).then(response => {
        this.tableData = response.data
        if (response.headers && response.headers['x-total-count']) {
          this.total = Number(response.headers['x-total-count'])
        }
        this.listLoading = false
      })
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleShowMoreComments(data) {
      this.historyCommentsListQuery.company_id = data.id
      this.getHistoryCommentsList(this.historyCommentsListQuery)
      this.dialogHistoryCommentsVisible = true
    },
    getHistoryCommentsList(query) {
      if (query && query.company_id) {
        API.company.comments(query).then(response => {
          this.history_comments = response.data
          if (response.headers && response.headers['x-total-count']) {
            this.historyCommentstotal = Number(response.headers['x-total-count'])
          }
        })
      } else {
        this.$message({
          showClose: true,
          message: '请先选择公司',
          type: 'warning'
        })
      }
    },
    handleHistoryCommentsSizeChange(val) {
      this.historyCommentsListQuery.limit = val
      this.getHistoryCommentsList(this.historyCommentsListQuery)
    },
    handleHistoryCommentsCurrentChange(val) {
      if (val >= 1) {
        this.history_comments_current_page = val
        this.historyCommentsListQuery.offset = (val - 1) * this.historyCommentsListQuery.limit
        this.getHistoryCommentsList(this.historyCommentsListQuery)
      }
    },
    handleCurrentChange(val) {
      if (val >= 1) {
        this.current_page = val
        this.listQuery.offset = (val - 1) * this.listQuery.limit
        this.getList()
      }
    },
    loadChildrenOptions({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        switch (parentNode.id) {
          default: /* empty */
            simulateAsyncOperation(() => {
              callback()
            })
        }
      }
    }
  }
}
</script>

<style scoped>
  .search-container{
    display: block;
    border: 1px solid #ebebeb;
    margin: 2px 2px 2px 2px;
  }
  .search-option-row{
    display: block;
    margin: 6px 0px 6px 6px;
  } 
  .search-option-label{
    display: inline-block;
    width: 8%;
    text-align: right;
  }
  .search-option-col{
    display: inline-block;
    width:  15%;
  }
  .search-button-row{
    display: block;
    margin: 2px 0px 2px 2px;
  }
  .search-button-label{
    display: inline-block;
    width: 8%;
    text-align: right;
  }
  .search-button-col{
    display: inline-block;
    width: 25%;
  }

  .table-header-row {
    display: block;
    border: 1px solid #ebebeb;
    margin: 2px 0px 2px 2px;
  }

  .table-header-button {
    display: inline-block;
    margin: 2px 0px 2px 2px;

  }

  .table-container{
    border: 1px solid #ebebeb;
    margin: 2px 2px 2px 2px;   
  }

  .select-item {
    display: inline-block;
    vertical-align: middle;
    min-width: 200px;
  }

  .form-row {
    display: block;
  }

  .form-item {
    width: 48%
  }

  .form-item-full {
    width: 100%
  }
</style>